package com.liu.design.structure.proxy;

import com.liu.design.structure.proxy.jdk.JdkProxyUtil;
import com.liu.design.structure.proxy.jdk.base.Target;
import com.liu.design.structure.proxy.jdk.base.TargetInterface;
import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/5/6 10:48
 * @description 查看代理类源文件
 * jdk动态代理采用字节重组，重新生成代理对象来替代原始对象。
 *    1.动态生成java代码
 *    2.编译生成新的.class文件
 *    3.重新加载到JVM内存中
 *
 */
public class JDKProxyTest {

    public static void main(String[] args) throws IOException {
        //jdk代理生成新的类
        TargetInterface proxy = (TargetInterface) JdkProxyUtil.getProxy(new Target());
        proxy.coreWork();


//        outClazz();
    }

    /**
     * 将内存中的字节码对象通过文件流输出到.class文件，查看其源代码
     * @throws IOException
     */
    private static void outClazz() throws IOException {
        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{Target.class});
        FileOutputStream os = new FileOutputStream("./11_design/$Proxy0.class");
        os.write(bytes);
        os.close();
    }
}
